//
//  JYRefreshControl.swift
//  weiboxiangmu
//
//  Created by wei_jingyun on 15/7/5.
//  Copyright © 2015年 wei_jingyun. All rights reserved.
//

import UIKit

private  let RefresText  = "正在加载数据..."
private  let PrepareText = "下拉刷新数据..."

class JYRefreshControl: UIRefreshControl {
    private  var finished : (() ->())?
    override init() {
        super.init()
        addSubview(prepareView)
        addSubview(refresView)
        self.tintColor = UIColor.clearColor()
        prepareView.center = self.center
        prepareView.setAll(UIImage(named: "tableview_pull_refresh")!, text: PrepareText)
        refresView.center = self.center
        refresView.setAll(UIImage(named: "tableview_loading")!, text: RefresText)
        // KVO 监听 自己
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }
    
    func refreshing(finished:() -> ()) -> JYRefreshControl {
        self.finished = finished
        
        addTarget(self, action: "valueChanged", forControlEvents: UIControlEvents.ValueChanged)
        
        return self
    }
    
    func valueChanged(){
        finished!()
    }
    
    deinit {
        // 注销监听
        removeObserver(self, forKeyPath: "frame")
    }
    /**
    1. 向下拉，y值会越来越小，Y值为负数，控件就会显示
    2. 拉到一定程度，会自动刷新
    3. 如果向上推表格，刷新控件仍然在，没有消失，Y值会一直变大
    */
    /// 显示提示图标标记
    private var showTipFlag = false {
        didSet{
            prepareView.rotateTipIcon(showTipFlag)
        }
    }
    
    /// 正在加载标记
    private var loadingFlag = false {
        didSet{
            showRefresView(loadingFlag)
        }
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            return
        }
        
        if frame.origin.y == 0 {
            loadingFlag = false
        }
       
        // 如果正在加载数据，就显示加载动画
        if refreshing && !loadingFlag {
            loadingFlag = true
            return
        }
        
        if (frame.origin.y < -50 && !showTipFlag) {
            showTipFlag = true
        } else if frame.origin.y >= -50 && showTipFlag {
            showTipFlag = false
        }
    }
    
    override func beginRefreshing() {
        valueChanged()
        super.beginRefreshing()
    }
    
    override func endRefreshing() {
        // 重设刷新标记
        loadingFlag = false
        refresView.stopLoadingAnim()
        super.endRefreshing()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    func showRefresView(show : Bool){
        refresView.hidden = !show
        prepareView.hidden = show
        if show {
            refresView.startLoadingAnim()
        }
    }
    
    lazy var prepareView = TipView(frame: CGRectMake(0, 0, 200, 44))
    lazy var refresView = TipView(frame: CGRectMake(0, 0, 200, 44))
}

class TipView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(tipIcon)
        addSubview(tipLabel)
        tipLabel.font = UIFont.systemFontOfSize(12)
        tipLabel.textColor = UIColor.darkTextColor()
        let iconTOlabel = 4 as CGFloat
        let iconWide = 40 as CGFloat
        tipIcon.ff_edgesView(UIedgeView().center(self, p: CGPoint(x: -(iconWide + iconTOlabel * 0.5) , y: 0)).size(iconWide, h: iconWide))
        tipLabel.ff_edgesView(UIedgeView().left(tipIcon, c: iconTOlabel).centerY(tipIcon, c: 0))
        
    }
    
    private func setAll(image : UIImage , text : String){
        tipIcon.image = image
        tipLabel.text = text
    }

    ///  旋转提示图标
    private func rotateTipIcon(clockWise: Bool) {
        
        var angle = M_PI
        angle += clockWise ? -0.01 : 0.01
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, CGFloat(angle))
        }
    }
    
    ///  开启加载动画
    private func startLoadingAnim() {
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        
       tipIcon.layer.addAnimation(anim, forKey: nil)
    }
    
    ///  停止动画
    private func stopLoadingAnim() {
        tipIcon.layer.removeAllAnimations()
    }
    
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var tipIcon = UIImageView()
    lazy var tipLabel = UILabel()
    
}


